package com.wsq.retrofitdemo.utils;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class GenerateSign {
    public static String generateSign(String openId, String openKey, String apiUrl, Map<String, String> paramMap) throws Exception {
        String sign = null;
        if ((openId == null) || ("".equals(openId.trim()))) {
            throw new Exception("openId 为空!");
        }
        if ((openKey == null) || ("".equals(openKey.trim()))) {
            throw new Exception("openKey 为空!");
        }
        // 创建参数列表
        Map<String, String> pMap = new HashMap();

        if (paramMap != null) {
            pMap.putAll(paramMap);
        }
        int i;
        String[] parmaArr;
        if ((apiUrl != null) && (apiUrl.indexOf("?") > 0)) {
            URL url = new URL(apiUrl);
            String urlParma = url.getQuery();
            if ((urlParma != null) && (!"".equals(urlParma.trim()))) {
                urlParma = URLDecoder.decode(urlParma, "utf-8");
                String[] urlParmaArr = urlParma.split("&");
                for (i = 0; i < urlParmaArr.length; i++) {
                    parmaArr = urlParmaArr[i].split("=");
                    if (!"openId".equals(parmaArr[0])) {
                        pMap.put(parmaArr[0], parmaArr.length > 1 ? parmaArr[1] :
                                "");
                    }
                }
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(openId);
        if ((pMap != null) && (!pMap.isEmpty())) {
            // 对参数名进行字典排序
            String[] keyArray = (String[]) pMap.keySet().toArray(new String[0]);
            Arrays.sort(keyArray);
            for (String key : keyArray) {
                String value = (String) pMap.get(key);
                if (value == null) {
                    value = "";
                }
                stringBuilder.append(key).append(
                        URLDecoder.decode(value, "utf-8"));
            }
        }
        // 拼接有序的参数名-值串
        stringBuilder.append(openKey);
        String codes = stringBuilder.toString();
        System.out.println("codes:" + codes);
        sign = SHA1Encode(codes);
//        System.out.println("sign:" + sign);
        return sign;
    }

    // SHA-1 编码， 这里使用的是 Apache codec，即可获得签名(shaHex()会首先将中文转换为 UTF8 编码然后进行 sha1 计算，使用其他的工具包请注意 UTF8 编码转换)
    private static String SHA1Encode(String input)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {
        try {
            if (input == null) {
                return null;
            }
            MessageDigest m = MessageDigest.getInstance("sha-1");
            m.update(input.getBytes("UTF-8"));
//            System.out.println("sha1:" + m.);
            byte[] s = m.digest();
            return hex(s);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw e;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw e;
        }
    }

    private static String hex(byte[] arr) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < arr.length; i++) {
            sb.append(Integer.toHexString(arr[i] & 0xFF | 0x100).substring(1,
                    3));
        }
        return sb.toString();
    }
}

